<template>
  <div class="pdl">
    <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" active-text-color="#33A0FF"
      text-color="#595959" :ellipsis="false" @select="handleSelect">
      <el-menu-item :index="index + ''" v-for="(item, index) in menuList" :key="index + ''">{{ item
      }}</el-menu-item>
    </el-menu>
    <div v-if="activeIndex == 0">
      <div class="info-main" v-show="infomainshow">
        <div class="flex">
          <div class="flex1"></div>
          <el-button type="primary" plain @click="infoshow = true; infomainshow = false">编辑</el-button>
        </div>
        <div class="flex">
          <div class="flex1 information">
            <div class="flex1  information-list">
              <div class="title">姓名</div>
              <div>{{ userInfo.name }}</div>
            </div>
            <div class="flex1  information-list">
              <div class="title">头像</div>
              <div class="avatar">
                <el-avatar :src="image" size="large" class="sidebar-head-img" v-if="!userInfo.avatar"></el-avatar>
                <el-avatar :src="userInfo.avatar" size="large" class="sidebar-head-img" v-else></el-avatar>
                <div class="you xue flex-center" v-if="userInfo.user_type == 1">学</div>
                <div class="you flex-center" v-else>游</div>
              </div>
            </div>
            <div class="flex1  information-list">
              <div class="title">年龄</div>
              <div>{{ userInfo.age }}</div>
            </div>
            <div class="flex1  information-list">
              <div class="title">单位</div>
              <div>{{ userInfo.company_name }}</div>
            </div>
            <div class="flex1  information-list">
              <div class="title">身份证号</div>
              <div>{{ userInfo.id_card }}</div>
            </div>
            <div class="flex1  information-list">
              <div class="title">个人介绍</div>
              <div class="duan">{{ userInfo.introduction }}</div>
            </div>
          </div>
          <div class="flex1 information">
            <div class="flex1  information-list">
              <div class="title">性别</div>
              <div>{{ userSex }}</div>
            </div>
            <div class="flex1  information-list">
              <div class="title">简历证件照</div>
              <div class="avatar">
                <el-avatar :src="userInfo.photo"></el-avatar>
              </div>
            </div>
            <div class="flex1  information-list">
              <div class="title">手机号</div>
              <div>{{ userInfo.mobile }}</div>
            </div>
            <div class="flex1  information-list">
              <div class="title">地址</div>
              <div>{{ areaNames }}{{ userInfo.address }}</div>
            </div>
            <div class="flex1  information-list">
              <div class="title">注册时间</div>
              <div>{{ userInfo.create_date }}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="info-main" v-show="infoshow">
        <div class="flex">
          <div class="flex1"></div>
          <el-button type="primary" plain @click="updateUserInfoSave">保存</el-button>
        </div>
        <el-form ref="ruleForm" :model="form" label-width="100px" class="flex" style="flex-direction: column;">
          <div class="flex">
            <div class="flex1 informations">
              <el-form-item label="头像">
                <div class="avatar">
                  <el-avatar :src="image" size="large" class="sidebar-head-img" v-if="!userInfo.avatar"></el-avatar>
                  <el-avatar :src="userInfo.avatar" size="large" class="sidebar-head-img" v-else></el-avatar>
                  <div class="you xue flex-center" v-if="userInfo.user_type == 1">学</div>
                  <div class="you flex-center" v-else>游</div>
                </div>
              </el-form-item>
              <el-form-item label="姓名">
                <el-input v-model="userInfo.name" type="text" disabled></el-input>
              </el-form-item>
              <el-form-item label="性别" prop="name">
                <el-select v-model="userInfo.sex" placeholder="请选择性别" size="large" :disabled="userInfo.user_type == 1">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="单位">
                <el-select v-model="userInfo.company_id" placeholder="请选择单位" size="large"
                  :disabled="userInfo.user_type == 1">
                  <el-option v-for="item in optionsData" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </div>
            <div class="flex1 informations">
              <el-form-item label="">
                <div class="avatar">
                </div>
              </el-form-item>
              <el-form-item label="身份证号码">
                <el-input v-model="userInfo.id_card" disabled></el-input>
              </el-form-item>
              <el-form-item label="年龄">
                <el-input v-model="userInfo.age" disabled></el-input>
              </el-form-item>
              <el-form-item label="注册时间">
                <el-input v-model="userInfo.create_date" disabled></el-input>
              </el-form-item>
              <!-- <el-form-item label="简历证件照">
              <div class="avatar">
                <el-avatar :src="userInfo.photo" @click="triggerFileInput"></el-avatar>
                <input type="file" ref="fileInput" style="display:none;" @change="uploadFile">
              </div>
            </el-form-item> -->
              <!-- <el-form-item label="手机号">
              <el-input v-model="userInfo.mobile" disabled></el-input>
            </el-form-item> -->
              <!-- <el-form-item label="地址">
              <el-cascader class="mb-4" v-model="userInfo.area" :options="cascaderOptions" :props="cascaderProps" clearable placeholder="请选择地区"/>
              <el-input v-model="userInfo.address" placeholder="请输入详细地址"></el-input>
            </el-form-item> -->
            </div>
          </div>

          <el-form-item label="个人介绍">
            <el-input type="textarea" v-model="userInfo.introduction"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
  <div v-if="activeIndex == 1" class="info-main">
    <div class="flex">
      <div class="flex1"></div>
      <div class="flex" v-if="verify_state == 1">
        <div class="flex1"></div>
        <div class="info-num">剩余{{ verify_num }}次</div>
        <el-button type="primary" plain @click="verify_state = 0" :disabled="verify_num == 0">重新认证</el-button>
      </div>
      <el-button v-else type="primary" plain @click="saveVerificationClick">完成认证</el-button>
    </div>
    <div v-if="verify_state == 1">
      <div class="flex-center info-img mb-5">
        <img src="../../assets/home/dui.png" alt="">
        <div>个人实名认证成功</div>
      </div>
    </div>
    <el-form ref="formRef" :model="form" :rules="rule" class="main-form">
      <el-form-item label="姓名" prop="name" required>
        <template #label>
          <div class="text-custom-text w-[65px]" style="text-align-last: justify;">姓名</div>
        </template>
        <el-input v-model="form.name" class="main-input"
          :disabled="verify_state == 1 || userInfo.user_type != 0"></el-input>
      </el-form-item>
      <el-form-item label="身份证号" prop="id_card" required>
        <template #label>
          <div class="text-custom-text w-[65px]" style="text-align-last: justify;">身份证号</div>
        </template>
        <el-input v-model="form.id_card" class="main-input" :disabled="verify_state == 1"></el-input>
      </el-form-item>
    </el-form>
  </div>
  <div v-if="activeIndex == 2">
    <password />
  </div>
</template>
<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { TokenUtil, TypeUtil } from '@/utils/common'
import ChinaCitys from '@/utils/ChinaCitys.json';
import axios from 'axios';
import password from '@/components/home/password.vue'
import { ElMessage } from 'element-plus';
import { userApi } from '@/api/modules/user.js'
import { useUserStore } from '@/stores/user';
const image = ref(new URL('@/assets/home/name.png', import.meta.url).href)
const userStore = useUserStore();
let userInfo = computed(() => userStore.userInfo);
const verify_num = ref('-')
const activeIndex = ref('0')
const menuList = ref(['个人信息', '实名认证', '修改密码'])
const infoshow = ref(false)
const optionsData = ref([])
const infomainshow = ref(true)
const verify_state = ref(null)
const cascaderOptions = ref(ChinaCitys)
const areaNames = ref('')
const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'children',
}
const props = defineProps({
  previewData: {
    type: Boolean,
    required: false,
    default: null
  },
  isResumePublic: Boolean
});
const options = [
  {
    value: '0',
    label: '女',
  },
  {
    value: '1',
    label: '男',
  }
]
// 文件输入框的引用
const fileInput = ref(null);
const formRef = ref(null)
const form = reactive({
  name: userInfo.value.name,
  id_card: userInfo.value.id_card,
})
const userSex = computed(() => {
  if (userInfo.value.sex === '1') {
    return '男'
  } else if (userInfo.value.sex === '0') {
    return '女'
  } else {
    return ''
  }
})

// 触发文件选择对话框的方法
const triggerFileInput = () => {
  fileInput.value.click();
};
const updateUserInfoSave = () => {
  // 地址验证
  if (!userInfo.value.area || userInfo.value.area.length === 0) {
    ElMessage.error('请选择所在地区');
    return;
  }

  // if (!userInfo.value.address || userInfo.value.address.trim() === '') {
  //   ElMessage.error('请输入详细地址');
  //   return;
  // }
  userApi.updateUserInfo({
    // photo: userInfo.value.photo,
    sex: userInfo.value.sex,
    introduction: userInfo.value.introduction,
    company: userInfo.value.company_id,
    // area: userInfo.value.area,
    // address: userInfo.value.address,
  }).then(res => {
    fetchData()
    infoshow.value = false
    infomainshow.value = true
    ElMessage.success('信息保存成功')
  });
}
const uploadFile = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  // 创建 FormData 对象并附加文件
  const formData = new FormData();
  formData.append('file', file);
  const modelDir = 'aiedu';
  try {
    // 使用模板字符串构建 URL 并发送 POST 请求
    const { data } = await axios.post(
      `${import.meta.env.VITE_APP_BASE_API}/upload/minio/${modelDir}`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
          'authorization': `${TokenUtil.getToken()}`
        },
      }
    );
    userInfo.value.photo = data.data.file_url;
    ElMessage.success('头像上传成功')
  } catch (error) {
    console.error('头像上传失败:', error);
  }
};
const fetchData = async () => {
  try {
    await userStore.fetchUserInfo();
    areaNames.value = getNamesByIds(userInfo.value.area);
  } catch (err) {
    console.log('Failed to fetch data:', err);
  }
};
const getcompanyOptionsList = async () => {
  try {
    const data = await userApi.getcompanyOptions();
    optionsData.value = data
  } catch (err) {
    console.log('Failed to fetch data:', err);
  }
}

// 身份证号码验证规则
const validateIdCard = (rule, value, callback) => {
  const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  if (!value) {
    callback(new Error('请输入身份证号码'))
  } else if (!reg.test(value)) {
    callback(new Error('请输入正确的身份证号码'))
  } else {
    callback()
  }
}

// 姓名验证规则
const validateName = (rule, value, callback) => {
  const reg = /^[\u4e00-\u9fa5]{2,4}$/
  if (!value) {
    callback(new Error('请输入真实姓名'))
  } else if (!reg.test(value)) {
    callback(new Error('请输入2-4个汉字'))
  } else {
    callback()
  }
}
const rule = {
  name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { validator: validateName, trigger: 'blur' }
  ],
  id_card: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    { validator: validateIdCard, trigger: 'blur' }
  ]
}
const saveVerificationClick = async () => {
  try {
    await formRef.value.validate()
    userApi.studentVerification({
      name: form.name,
      id_card: form.id_card
    }).then(res => {
      if (TypeUtil.isNumber(res)) {
        verify_num.value = res
      } else {
        verify_num.value = res.data
      }
      verify_state.value = 1
      fetchData()
      ElMessage.success('认证提交成功')
    });
  } catch (error) {

  }
}
// 通过ID数组查询对应的名称
const getNamesByIds = (ids) => {
  if (!ids || !Array.isArray(ids)) return [];

  const names = [];

  // 遍历每个ID进行查询
  for (const id of ids) {
    // 递归查找函数
    const findNameById = (data, targetId) => {
      for (const item of data) {
        if (item.id === targetId) {
          return item.name;
        }

        if (item.children && item.children.length > 0) {
          const foundName = findNameById(item.children, targetId);
          if (foundName) return foundName;
        }
      }
      return null;
    };

    const name = findNameById(cascaderOptions.value, id);
    if (name) names.push(name);
  }

  return names.join('');
};
onMounted(() => {
  verify_num.value = userInfo.value.verify_num
  verify_state.value = userInfo.value.verify_state

  fetchData();
  getcompanyOptionsList()
});
const handleSelect = (key, keyPath) => {
  activeIndex.value = key
}
</script>
<style lang="scss" scoped>
.el-menu-demo :deep(.el-menu-item:hover),
.el-menu-demo :deep(.el-menu-item.is-active),
.el-menu-demo :deep(.el-menu-item:focus) {
  background-color: transparent !important;
  /* 取消背景颜色变化 */
}

.el-menu-demo :deep(.is-active) {
  background-color: transparent !important;
}

.pdl {
  display: flex;
  padding-right: 20px;
  flex-direction: column;
  // height: 100%;
}

.avatar {
  position: relative;
  width: 96px;
  height: 96px;

  :deep(.el-avatar) {
    width: 96px;
    height: 96px;
  }

  .you {
    position: absolute;
    top: 0;
    right: 0;
    width: 24px;
    font-size: 14px;
    height: 24px;
    background: linear-gradient(321deg, #0A886D 0%, #25D5AF 100%);
    border-radius: 12px;
    border: 1px solid #FFFFFF;
    color: #fff;
    text-align: center;
  }

  .xue {
    right: -35px;
    background: linear-gradient(316deg, #0765B8 0%, #33A0FF 100%);
  }
}

.info-main {
  //margin-top: 24px;
  box-sizing: border-box;
  padding-right: 20px;

  .info-num {
    font-weight: 400;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.65);
    margin-right: 16px;
    line-height: 30px;
  }

  .info-img {
    font-family: MiSans, MiSans;
    font-weight: 500;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.88);
    margin-top: 50px;

    img {
      width: 32px;
      height: 32px;
      margin-right: 16px;
    }
  }

  .main-form {
    margin: 40px auto 0;
    width: 400px;
    text-align: center;
  }

  .main-input {
    width: 292px;
  }

  .informations {
    // cursor: pointer;
    // margin-left: 30px;
    margin-top: 30px;

    :deep(.el-select--large .el-select__wrapper) {
      height: 30px !important;
      min-height: 30px !important;
    }

    :deep(.el-textarea__inner) {
      height: 96px;
      resize: none;
    }

    :deep(.el-form-item) {
      position: relative !important;
    }
  }

  .information {
    padding-left: 30px;
    font-family: MiSans, MiSans;
    font-weight: bold;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.88);

    .information-list {
      margin-top: 20px;
      display: flex;

      .duan {
        width: 320px;
      }
    }

    .title {
      width: 70px;
      text-align: right;
      font-family: MiSans, MiSans;
      font-weight: 400;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.45);
      margin-right: 8px;
      text-align: left;
    }
  }
}
</style>